import { defineStore } from 'pinia';
import { encryption, storage } from '@/utils';
import { loginByUsername, getUserInfo, loginOut } from '@/views/login/api';

export const useUserInfo = defineStore(
  'userInfo',
  () => {
    const data = reactive({
      permissions: [],
      roles: [],
      sysUser: {},
    });
    const userName = computed(() => data.sysUser?.username);
    // 登录
    const login = (params) => {
      const user = encryption({
        data: params,
        key: 'thanks,pig4cloud',
        param: ['password'],
      });

      return loginByUsername(user).then((res) => {
        Object.assign(data, { ...res });
        storage.set('tsp-access_token', res.access_token);
      });
    };
    // 查询用户
    const queryUserInfo = () => {
      getUserInfo().then((res) => {
        const { permissions, roles, sysUser } = res;
        data.permissions = permissions;
        data.roles = roles;
        data.sysUser = sysUser;
      });
    };
    //登出
    const handleLoginOut = () => {
      loginOut().then(() => {
        storage.clear();
      });
    };

    return { data, userName, login, queryUserInfo, handleLoginOut };
  },
  {
    persist: true,
  }
);
